package com.woniu.serviceorder.service.serviceImpl;

import com.woniu.internalcommon.dto.ResponseResult;
import com.woniu.internalcommon.request.DriverGrabRequest;
import com.woniu.serviceorder.service.GrabService;
import com.woniu.serviceorder.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

@Service("grabByRedissonBasicService")
@Slf4j
public class GrabByRedissonBasicServiceImpl implements GrabService {
    @Autowired
    OrderService orderService;

    @Autowired
    @Qualifier("redissonBootYaml")
    RedissonClient redissonClient;
    @Override
    public ResponseResult grab(DriverGrabRequest driverGrabRequest) {

        String orderId = driverGrabRequest.getOrderId() + "";
        String key = orderId;
        RLock lock = redissonClient.getLock(key);
        lock.lock();

        try {
            log.info("开始锁redis redisson basic");

            // 执行抢单操作
            ResponseResult grab = orderService.grab(driverGrabRequest);

            log.info("结束锁redis redisson basic");

            return grab;
        } catch (Exception e) {
            log.error("抢单操作失败，回滚事务", e);
            // Seata 会自动回滚事务，但如果需要，可以在这里进行一些自定义的异常处理
            return ResponseResult.fail("抢单失败");
        } finally {
            // 确保锁被释放
            // 确保锁释放在事务提交后进行
            if (lock.isLocked()) {
                lock.unlock();
            }
        }
    }
}
